<template>
  <div>
    <Modal
      v-model='showStatus'
      :title="(!isEdit ? '添加' : '编辑') + '资源信息'"
      @on-ok='ok'
      @on-cancel='cancel'
      :loading='loading'
    >
      <Form
        :model='localItem'
        :label-width='80'
        :rules='ruleValidate'
        ref='table'
      >
        <FormItem label='资源名称' prop='name'>
          <Input v-model='localItem.name' placeholder='请输入资源名称'></Input>
        </FormItem>
        <FormItem label='排序' prop='sort'>
          <i-input v-model='localItem.sort' placeholder='组件默认排序' />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import { resourceCateDispatch } from '@/api/admin'

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    isShow: {
      type: Boolean,
      default: false
    },
    item: {
      type: Object,
      default: () => {
      }
    }
  },
  watch: {
    item(newVal, oldVal) {
      this.localItem = { ...newVal }
    },
    isShow() {
      this.showStatus = this.isShow
    }
  },
  data() {
    return {
      loading: true,
      showStatus: false,
      localItem: {
        name: '',
        sort: 0
      },
      ruleValidate: {
        name: [{ required: true, message: '请输入资源分类名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    ok() {
      this.$refs.table.validate((valid) => {
        if (valid) {
          this.loading = false
          console.log(this.isEdit)
          if (!this.isEdit) {
            resourceCateDispatch.use('add', this.localItem).then((res) => {
              if (res.code === 200) {
                this.$emit('changeEvent', false)
                this.initForm()
                this.$emit('editEvent', { ...this.localItem })
                this.$Message.success('添加成功！')
              }
            })
          } else {
            resourceCateDispatch.use('update', this.localItem).then((res) => {
              if (res.code === 200) {
                this.$emit('changeEvent', false)
                this.initForm()
                this.$emit('editEvent', { ...this.localItem })
                this.$Message.success('修改成功！')
              }
            })
          }
        } else {
          this.loading = false
          this.$nextTick(() => (this.loading = true))
          this.$Message.error('请检查输入数据')
        }
      })
    },
    cancel() {
      this.initForm()
      this.$emit('changeEvent', false)
      this.$Message.info('取消编辑！')
    },
    initForm() {
      this.$refs.table.resetFields()
      this.localItem = {
        name: '',
        sort: 0
      }
    }
  }
}
</script>
